<?php

namespace app;

class Log
{
    private $logFile;
    private $dir;

    public function __construct($dir)
    {
//        $this->dir = "/mnt/supplier-system/".$dir."/".date("Ymd");
        $this->dir = app()->getRuntimePath()."sys_log/".$dir."/".date("Ymd");
        if (!file_exists($this->dir)) {
            mkdir($this->dir, 0777, true);
        }
        $this->setFile();
    }

    protected function setFile()
    {
        $this->logFile = $this->dir.date("/H").".log";
    }


    public function write($content, $type = "info")
    {
        $info = "+[date] " . date(DATE_ATOM) . " [ip] " . $this->get_client_ip() . " [type] " . $type . " [timer] ".bcsub(microtime(true),request()->server("REQUEST_TIME_FLOAT"),4).PHP_EOL;
        foreach ($content as $k=>$v){
            $info .= "+[".$k."] ". $this->serializeData($v).PHP_EOL;
        }
        $info .= $this->line() . PHP_EOL;
        file_put_contents($this->logFile, $info, FILE_APPEND);
    }

    protected function line(): string
    {
//        添加20个减号作为分割线
        return "+" . str_repeat("-·", 60);
    }

    protected function serializeData($data)
    {
        return is_array($data)?json_encode($data,320):(is_string($data)?$data:var_export($data,true));
    }

    private function get_client_ip()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return ($ip);
    }
}
